import { PayloadAction, createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { RootState } from '../store';

interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0,
};

// thunk createAsyncThunk
// 允许返回一个 Promise
export const fetchCounts = createAsyncThunk(
  'counts/fetcher',
  async (v: number) => {
    return new Promise<number>((relove) => {
      setTimeout(() => {
        relove(v);
      }, 2000);
    });
  }
);

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    add(state) {
      state.value++;
    },
    remove(state) {
      state.value--;
    },
    de(state, action: PayloadAction<number>) {
      state.value = action.payload;
    },
  },
  extraReducers(builder) {
    builder
      .addCase(fetchCounts.pending, (state, action) => {
        console.log(state.value, action);
        state.value = -999999999;
      })
      .addCase(fetchCounts.fulfilled, (state, action) => {
        state.value = action.payload;
      })
      .addCase(fetchCounts.rejected, (state, action) => {
        console.error('报错了', state, action);
      });
  },
});

// select 选择器
export const selectCount = (state: RootState) => state.counter.value;
